import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:zhibao_flutter/util/event_bus/number_event.dart';
import 'package:zhibao_flutter/widget/view/dynamic_number.dart';
import 'package:zhibao_flutter/widget/view/my_gradent_text.dart';
import 'package:zhibao_flutter/zone.dart';

Future priceDialog(String initValue) {
  return Get.dialog(
    PriceDialog(initValue),
    useSafeArea: false,
    barrierColor: Colors.transparent,
  );
}

class PriceDialog extends StatefulWidget {
  final String initValue;

  PriceDialog(this.initValue, {Key? key}) : super(key: key);

  @override
  State<PriceDialog> createState() => _PriceDialogState();
}

class _PriceDialogState extends State<PriceDialog> {
  RxString textValue = "0.00".obs;

  static double fullHeight = 300.px;

  StreamSubscription? eventBusOfNumBerValue;

  List<String> list = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '',
    '0',
    'Del'
  ];

  @override
  void initState() {
    super.initState();
    textValue.value = widget.initValue;
    // 【价格输入框】这个输入，可以默认空，不然每次还要删除0.00这个这个字符串
    if (textValue.value == "0.00") {
      textValue.value = "0";
    }
    eventBusOfNumBerValue =
        eventBusOfNumBer.on<RefreshHomePriceModel>().listen((event) {
      if (mounted) setState(() {});
    });
  }

  // Data less than 1000, need to remove the thousandth sign.
  void removeThousandthSign() {
    print("[handleData] removeThousandthSign::call");
    if (!textValue.value.contains(',')) {
      return;
    }

    /// Remove ","
    if (double.parse(textValue.value.replaceAll(',', '')) < 1000) {
      print("Data less than 1000, need to remove the thousandth sign.");
      textValue.value = textValue.value.replaceAll(",", '');
    } else {
      addThousandthSign();
    }
  }

  // The value is greater than 1000.
  void addThousandthSign() {
    print("[handleData] addThousandthSign::call");
    final useOriginValue = textValue.value.replaceAll(',', '');
    if (double.parse(useOriginValue) > 1000) {
      print("The value is greater than 1000.");
      final startNumber =
          useOriginValue.substring(0, useOriginValue.length - 3);
      final end3Number = useOriginValue.substring(
          useOriginValue.length - 3, useOriginValue.length);
      print("startNumber::$startNumber,end3Number::$end3Number");
      textValue.value = startNumber + "," + end3Number;
      // eventBusOfNumBer.fire(
      //     EventBusOfNumBerModel(
      //         "1000", 0, 0));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10.px)),
            ),
            height: FrameSize.winHeight() * 0.9,
            child: SafeArea(
              top: false,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  SizedBox(height: 10.px),
                  Text(
                    '',
                    style: TextStyle(color: Colors.grey, fontSize: 13.px),
                  ),
                  Expanded(
                    child: Center(
                      child: Container(
                        height: 300.px,
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(horizontal: 5.px),
                        child: () {
                          final double fontSize = textValue.value.length < 4

                              /// If set 100 will be overflow.
                              ? 80.px
                              : textValue.value.length < 6
                                  ? 75.px
                                  : textValue.value.length < 7
                                      ? 70.px
                                      : textValue.value.length < 8
                                          ? 60.px
                                          : textValue.value.length < 9
                                              ? 55.px
                                              : textValue.value.length < 10
                                                  ? 50.px
                                                  : 45.px;
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                height: fullHeight / 3,
                                alignment: Alignment.center,
                                child: MyGradentText(
                                  "\$",
                                  style: TextStyle(
                                    fontSize: fontSize,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                              ...List.generate(textValue.value.length, (index) {
                                final useValue = textValue.value[index];
                                final substring =
                                    textValue.value.substring(0, index);
                                print("substring::$substring");
                                int whenCurrentValueNum = 0;
                                for (int i = 0; i < substring.length; i++) {
                                  if (substring[i] == useValue) {
                                    whenCurrentValueNum =
                                        whenCurrentValueNum + 1;
                                  }
                                }
                                final keyUse =
                                    "useValue[$useValue],whenCurrentValueNum[$whenCurrentValueNum]";
                                print(
                                    "Real use the key is ${json.encode(keyUse)}");

                                return DynamicNumber(
                                  fullHeight,
                                  fontSize,
                                  index,
                                  useValue,
                                  key: ValueKey(index == 0
                                      ? "first"
                                      : useValue == ","
                                          ? index
                                          : "$keyUse"),
                                  // key: ValueKey(
                                  //     index == 0 ? "first" : '$index::$useValue'),
                                );
                              }),
                            ],
                          );
                        }(),
                        // child: Obx(() {
                        //   return MyGradentText(
                        //     "\$" + textValue.value,
                        //     style: TextStyle(
                        //       fontSize:
                        //           100.px - ((textValue.value.length - 4) * 10),
                        //       fontWeight: FontWeight.w600,
                        //     ),
                        //   );
                        // }),
                      ),
                    ),
                  ),
                  Container(
                    height: 42.px,
                    width: FrameSize.winWidth(),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          Color(0xffeae7e8),
                          Color(0xffdcd9da),
                        ],
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        InkWell(
                          child: Padding(
                            padding: EdgeInsets.symmetric(horizontal: 20.px),
                            child: MyGradentText(
                              'complete'.tr,
                              style: TextStyle(
                                  fontSize: 25.px, fontWeight: FontWeight.w600),
                              colors: MyTheme.mainGradientColor(),
                            ),
                          ),
                          onTap: () {
                            Get.back(result: textValue.value);
                          },
                        ),
                      ],
                    ),
                  ),
                  new Container(
                    width: MediaQuery.of(context).size.width,
                    alignment: Alignment.center,
                    color: Colors.white,
                    padding: EdgeInsets.symmetric(
                        horizontal: 20.px, vertical: 15.px),
                    child: Wrap(
                      alignment: WrapAlignment.spaceBetween,
                      runSpacing: 10.px,
                      spacing: 10.px,
                      children: List.generate(list.length, (index) {
                        final valueUse = list[index];
                        return InkWell(
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(
                                      valueUse == "" || valueUse == "Del"
                                          ? 0
                                          : 0.3),
                                  offset: Offset(0, 5),
                                  blurRadius: 10,
                                )
                              ],
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10.px)),
                            ),
                            alignment: Alignment.center,
                            height: 50.px,
                            width: 100.px,
                            child: valueUse == "Del"
                                ? Icon(CupertinoIcons.delete_left,
                                    color: MyTheme.mainGradientColor()[0],
                                    size: 25.px)
                                : Text(
                                    "$valueUse",
                                    style: TextStyle(
                                        fontSize: 18.px,
                                        fontWeight: FontWeight.bold),
                                  ),
                          ),
                          onTap: index == 11
                              ? () {
                                  if (textValue.value.trim() != "" &&
                                      textValue.value.trim() != "0") {
                                    if (textValue.value.trim().length == 1) {
                                      textValue.value = "0";
                                      eventBusOfNumBer.fire(
                                          EventBusOfNumBerModel("0", 0, 0));
                                      return;
                                    }

                                    /// Remove ".".
                                    if (textValue.value.length > 2) {
                                      final endStr = textValue.value.substring(
                                          textValue.value.length - 2,
                                          textValue.value.length - 1);
                                      print("endStr::$endStr");
                                      if (endStr == ".") {
                                        textValue.value = textValue.value
                                            .substring(
                                                0, textValue.value.length - 1);
                                        eventBusOfNumBer.fire(
                                            EventBusOfNumBerModel(null, 1,
                                                textValue.value.length));
                                      }
                                    }

                                    textValue.value = textValue.value.substring(
                                        0, textValue.value.length - 1);
                                    eventBusOfNumBer.fire(EventBusOfNumBerModel(
                                        null, 1, textValue.value.length));

                                    removeThousandthSign();
                                  }
                                }
                              : () {
                                  if (list[index] != "" &&
                                      list[index] != "Del") {
                                    if (textValue.value.length >= 10) {
                                      myToast('Maximum limit exceeded');
                                      return;
                                    }

                                    if (textValue.value.trim() == "0") {
                                      textValue.value = list[index];
                                      eventBusOfNumBer.fire(
                                          EventBusOfNumBerModel(
                                              list[index], 0, 0));
                                    } else {
                                      /// 更新输入框的值
                                      textValue.value += list[index];
                                      setState(() {});

                                      eventBusOfNumBer.fire(
                                          EventBusOfNumBerModel(list[index], 0,
                                              textValue.value.length - 1));
                                      addThousandthSign();
                                    }

                                    /// 保持光标
                                    // lastCursor(
                                    //     textEditingController:
                                    //         controller);
                                  }
                                },
                        );
                      }),
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    eventBusOfNumBerValue?.cancel();
    eventBusOfNumBerValue = null;
  }
}
// number_keypan.dart =》文件内容如下：

// import 'package:flutter/material.dart';

/// <summary>
/// todo: 数字键盘
/// author：zwb
/// dateTime：2021/7/19 10:25
/// filePath：lib/widgets/number_keypan.dart
/// desc: 示例
/// <summary>
// OverlayEntry overlayEntry;
// TextEditingController controller = TextEditingController();
//
// numberKeypan(
//   initialization: (v){
//     /// 初始化
//     overlayEntry = v;
//     /// 唤起键盘
//     openKeypan(context: context);
//   },
//   onDel: (){
//     delCursor(textEditingController: controller);
//   },
//   onTap: (v){
//     /// 更新输入框的值
//     controller.text += v;
//     /// 保持光标
//     lastCursor(textEditingController: controller);
//   },
// );

/// <summary>
/// todo: 保持光标在最后
/// author: zwb
/// date: 2021/7/19 11:43
/// param: 参数
/// return: void
/// <summary>
///
lastCursor({required TextEditingController textEditingController}) {
  /// 保持光标在最后
  final length = textEditingController.text.length;
  textEditingController.selection =
      TextSelection(baseOffset: length, extentOffset: length);
}
